package com.niubility.controller;

import com.niubility.entity.Follow;
import com.niubility.entity.Lable;
import com.niubility.exception.CustomException;
import com.niubility.server.IArticleServer;
import com.niubility.server.IFollowServer;
import com.niubility.server.ILabService;
import com.niubility.vo.ArticleAll;
import com.niubility.vo.LoadAll;
import com.niubility.vo.ResultAndTag;
import com.niubility.vo.TrueFalse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static net.sf.json.JSONObject.fromObject;

@Controller
public class LabController {
    @Autowired
    private ILabService labService;
    @Resource
    private IFollowServer followServer;

    @Resource
    private IArticleServer articleServer;

    Logger logger = Logger.getLogger("LabController");

    //增加标签
    @RequestMapping("/addLab")
    public void addLab(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        Lable lable=new Lable();
        String callback=req.getParameter("callback");
        lable.setLabName(req.getParameter("labName"));
        lable.setLabPicture(req.getParameter("labPicture"));
        TrueFalse isSuccess=new TrueFalse();
        String result=null;
        try {
            isSuccess.setSuccess(labService.addLab(lable));
            result = callback + "(" + JSONObject.fromObject(isSuccess).toString() + ")";
        }catch (Exception e){
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();

        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //删除标签
    @RequestMapping("/deleteLab")
    public void delLabById(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");
        String[] labIds=req.getParameter("labIds").split(",");
        //System.out.println(labIds.length);
        int[] labId=new int[labIds.length];
        for(int i=0;i<labIds.length;i++){
            labId[i]=Integer.parseInt(labIds[i]);
        }
        TrueFalse trueFalse=new TrueFalse();

        String result=null;
        try {
            trueFalse.setSuccess(labService.delLabById(labId));
            result = callback + "(" + JSONObject.fromObject(trueFalse) + ")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //修改标签
    @RequestMapping("/updateLab")
    public void updateLab(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");
        Lable lable=new Lable();
        lable.setLabName(req.getParameter("labName"));
        lable.setLabId(Integer.parseInt(req.getParameter("labId")));
        lable.setLabPicture(req.getParameter("labPicture"));
        TrueFalse trueFalse=new TrueFalse();

        String result=null;
        try {
            trueFalse.setSuccess(labService.update(lable));
            result = callback + "(" + JSONObject.fromObject(trueFalse) + ")";
            resp.getWriter().write(result);
        }catch (Exception e){
            result=callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //按ID查找标签
    @RequestMapping("/loadLabById")
    public void loadLabById(HttpServletRequest req,HttpServletResponse resp) throws CustomException {

        String callback=req.getParameter("callback");
        int labId= Integer.parseInt(req.getParameter("labId"));

        String result=null;
        try {
            Lable lable = labService.loadLabById(labId);
            result = callback + "(" + JSONObject.fromObject(lable) + ")";
            resp.getWriter().write(result);
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw  new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //查看全部标签
    @RequestMapping("/loadAllLab")
    public void loadAllLab(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");

        String result=null;
        try {
            List<Lable> lableList = labService.loadAllLab();
            result = callback + "(" + JSONArray.fromObject(lableList) + ")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //查询该用户关注的社区的文章，显示按时间顺序排序，首页显示5篇，后续加载每一页十篇
    @RequestMapping("/loadArt")
    public void loadArt(HttpServletRequest req , HttpServletResponse resp){
        String callback=req.getParameter("callback");
        Set<Integer> Id=new HashSet<Integer>();
        int page=Integer.parseInt(req.getParameter("page"));
        List<ArticleAll> articleAllList=null;
        LoadAll loadAll = new LoadAll();
        if(req.getParameter("labId")!=null) {
            Id.add(Integer.parseInt(req.getParameter("labId")));
        }
        else{
            if(req.getSession().getAttribute("userId")!=null) {
                Integer acountId = (Integer) req.getSession().getAttribute("userId");

                int[] labId = followServer.FollowLabId(acountId);
                if (labId.length == 0) {
                    articleAllList = articleServer.SelectByRecommend(page, 11, 0, 0, 0, 2, null);
                } else {

                    Id = labService.loadAllArtId(labId);
                    int[] artId = new int[Id.size()];
                    for (int i = 0; i < artId.length; i++) {
                        artId[i] = (Integer) Id.toArray(new Integer[0])[i];
                    }
                    articleAllList = articleServer.SelectByRecommend(page, 11, 0, 0, 0, 6, artId);
                }
            }else{
                articleAllList = articleServer.SelectByRecommend(page, 11, 0, 0, 0, 2, null);
            }
            if(articleAllList.size()<11){
                loadAll.setList(articleAllList);
                loadAll.setPageMore(0);
            }else{
                loadAll.setList(articleAllList.subList(0,10));
                loadAll.setPageMore(1);
                try {
                    resp.getWriter().write(callback+"("+JSONArray.fromObject(loadAll).toString()+")");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }





    //头部新社区推荐
    @RequestMapping("/recommendNewCommu")
    public void loadNewLab(HttpServletRequest req, HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");
        int commuCounts= Integer.parseInt(req.getParameter("newCommuCounts"));
        String result=null;
        try {
            List<Lable> lableList = labService.loadNewCommu(commuCounts);
            result = callback + "(" + JSONArray.fromObject(lableList).toString() + ")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //热门社区显示
    @RequestMapping("/hotCommu")
    public void loadHotLab(HttpServletRequest req,HttpServletResponse resp) throws CustomException {
        String callback=req.getParameter("callback");
        int page= Integer.parseInt(req.getParameter("page"));
        int counts=Integer.parseInt(req.getParameter("displayCounts"));
        //System.out.println(page);
        //System.out.println(counts);
        Boolean hasNext=true;
        String result = null;
        try {
            List<Lable> lableList = labService.loadHotCommu(page, counts);
            ResultAndTag<Lable> resultAndTagResult = new ResultAndTag<Lable>();
            if (lableList.size() < counts + 1) {
                hasNext = false;
            }
            resultAndTagResult.setHasNext(hasNext);
            if (lableList.size() < counts) {
                resultAndTagResult.setList(lableList);
            } else {
                resultAndTagResult.setList(lableList.subList(0, counts));
            }
            result = callback + "(" + JSONObject.fromObject(resultAndTagResult) + ")";
        }catch (Exception e){
            result = callback+"("+"{\"returncade\":"+"108}"+")";
            try {
                resp.getWriter().write(result);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new CustomException();
        }
        try {
            resp.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
